import _ from "lodash";
// 标点列表
const punctuationList = [",", ".", "?", "!", ";", ":"];
let pattStr = punctuationList.join("\\");
//标点正则
const punctuationPatt = new RegExp(`\\s*[${pattStr}]\\s+`, "g");
// 随机函数（打乱单词顺序）
const randomOptionList = function(arr, number) {
  if (!number && number != 0) {
    number = 10;
  }
  let data = _.shuffle(arr);
  number--;
  if (data.length > 1 && number) {
    let isSample = data.every((item, index) => {
      return item == arr[index];
    });
    while (isSample) {
      return randomOptionList(arr, number);
    }
  }
  return data;
};
// 切分处理句子
const setSentenceToWord = function(sentence) {
  if (Object.prototype.toString.call(sentence) !== "[object String]") {
    throw new Error("不是字符串");
  }
  let wordList = [],
    optionList = [],
    answerList = [];
  let str = (sentence + " ").replace(punctuationPatt, function(punctuation) {
    return " " + punctuation.trim() + " ";
  });
  let sentenceData = str
    .trim()
    .split(" ")
    .map((item) => {
      return item.trim();
    });
  wordList = sentenceData;
  optionList = randomOptionList(
    wordList
      .filter((item) => {
        return punctuationList.indexOf(item.trim()) == -1;
      })
      .map((item, index) => {
        return {
          word: item,
          isChecked: false,
          index,
        };
      })
  );
  answerList = wordList.map((item, index) => {
    if (punctuationList.indexOf(item.trim()) != -1) {
      return {
        trueWord: item,
        checkedOption: null,
        isTrue: true,
        isPunctuation: true,
        index,
      };
    } else {
      return {
        trueWord: item,
        checkedOption: null,
        isTrue: false,
        isPunctuation: false,
        index,
      };
    }
  });
  return { wordList, optionList, answerList };
};
export { setSentenceToWord, punctuationList, punctuationPatt };
